<template>
  <div class="uploadworkbox">
    <el-dialog 
      :model-value="isDialogVisible" 
      title="创建新作品"
      :before-close="beforeClose"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
       
        <el-form-item label="作品名称：" prop="newWorkName">
          <div class="width:50%">
            <el-input v-model="form.newWorkName"></el-input>
          </div>
        </el-form-item>

        <el-form-item label="性别向：" prop="genderOrientation">
          <el-radio-group v-model="form.genderOrientation">
            <el-radio label="男生">男生向</el-radio>
            <el-radio label="女生">女生向</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="作品简介：" prop="workDescription">
          <el-input 
            type="textarea"
            v-model="form.workDescription"
            show-word-limit
            maxlength="120"
            rows="4"
            resize="none"
          ></el-input>
        </el-form-item>
        <!-- 标签选择 -->
        <el-form-item label="标签选择：" prop="workCategories">
          <!-- 多选标签 -->
          <div class="tag-group">
            <!-- 循环显示标签选项 -->
            <el-tag
              v-for="(tag, index) in tagOptions"
              :key="index"
              closable
              @click="handleChecks(tag)"
              :class="{ active: tag.checked }"
              effect="plain"
              @close="handleClose(tag)"
            >
              {{ tag.labelName.length > 5 ? tag.labelName.substring(0, 5) + '...' : tag.labelName }}
            </el-tag>
          </div>
        </el-form-item>

        <!-- 自定义标签输入框 -->
        <el-form-item prop="customTagInput">
          <el-input
            placeholder="自定义标签(最多可输入6个字符)"
            maxlength="6"
            v-model="form.customTagInput"
          >
            <!-- 添加按钮 -->
            <template #append>
              <el-button @click="addCustomLabel(form.customTagInput)">添加</el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="上传封面：" prop="fileList">
          <el-upload 
            class="avatar-uploader" 
            list-type="picture-card" 
            :auto-upload="false"
            accept="image/jpeg,image/gif,image/png"
            :on-preview="handlePictureCardPreview" 
            :on-remove="handleRemove" 
            :on-change="handleChange"
            limit=1
            :file-list="form.fileList"
          >
          </el-upload>
          <el-dialog :model-value="dialogVisibleImg" :before-close="previewClose" append-to-body width="30%">
            <img :src="dialogImageUrl" >
          </el-dialog>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">修改信息</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance,onMounted,watch } from 'vue';
import { ElMessage } from 'element-plus';

const { proxy } = getCurrentInstance();

const props = defineProps({
  isDialogVisible: {
    type: Boolean,
    default: false
  },
  currentBook: Object
});

const emit = defineEmits(['update:isDialogVisible','update:currentBook']);
const formRef = ref(null);

// 添加书籍文件的响应式引用
const form = ref({
  newWorkName: '',
  genderOrientation: '',
  workDescription: '',
  workCategories: [],
  customTagInput: '',
  fileList: [],
});

const rules = {
  newWorkName: [
    { required: true, message: '作品名称必须在1到12个字符之间', trigger: ['blur', 'change'], min: 1, max: 12 }
  ],
  genderOrientation: [
    { required: true, message: '必须选择性别向', trigger: 'blur' }
  ],
  workDescription: [
    { required: true, message: '作品简介不能为空', trigger: 'blur' }
  ],
  workStatus: [
    { required: true, message: '必须选择作品状态', trigger: 'blur' }
  ],
  workCategories: [
    {required:true,validator: (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error('至少选择一个作品标签'));
      } else {
        callback();
      }
    }, trigger: 'change' }
  ],
  customTagInput:[
    {max:6,message:'标签字数不多于6个',trigger:'change'}
  ],
  fileList: [
    { required: true, message: '必须上传封面', trigger: 'blur' }
  ]
};
const dialogImageUrl = ref('');
const dialogVisibleImg = ref(false);
const tagOptions = ref([
  { labelName: '历史', checked: false },
  { labelName: '玄幻', checked: false },
  { labelName: '言情', checked: false },
  { labelName: '科幻', checked: false },
]);


//选择标签
const handleChecks = (tag) => {
  tag.checked = !tag.checked;
  if (tag.checked) {
    form.value.workCategories.push(tag.labelName);
  } else {
    form.value.workCategories = form.value.workCategories.filter(t => t !== tag.labelName);
  }
};
//删除标签
const handleClose = (tag) => {
  if(tagOptions.value.length>1){
    tagOptions.value = tagOptions.value.filter(t => t !== tag);
    form.value.workCategories = form.value.workCategories.filter(t => t !== tag.labelName);
  }
};
//添加自定义标签
const addCustomLabel = (val) => {
  if (val && !tagOptions.value.some(tag => tag.labelName === val)) {
    tagOptions.value.push({ labelName: val, checked: false });
    form.value.customTagInput = '';
  }
};

//修改封面
const handleChange = (file, fileList) => {
  form.value.fileList = fileList;
  document.querySelector('.el-upload').style.display = 'none';
  console.log('文件变更:', fileList);
};
//和预览相关的
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisibleImg.value = true;
  console.log("预览成功");
};
const previewClose = () => {
  dialogVisibleImg.value = false;
};
const handleRemove = (file, fileList) => {
  dialogVisibleImg.value = false;
  document.querySelector('.el-upload').style.display = 'block';
  console.log(file, fileList);
};

// 整个表单窗口关闭
const beforeClose = () => {
  emit('update:isDialogVisible', false);
};

// 在文件选择前执行
const beforeBookUpload = (file) => {
  const isEpubOrPdf = file.type === 'application/epub+zip' || file.type === 'application/pdf';
  if (!isEpubOrPdf) {
    ElMessage.error('只支持EPUB或PDF格式的书籍');
    return false;
  }
  form.value.bookFile = file;  // 保存文件到表单数据
  return false; // 阻止组件自动上传
};

//提交表单
const submitForm = async () => {
  await formRef.value.validate(async (valid) => {
    if (valid) {
        await proxy.$http.post('/api/book/create', {
          name: form.value.newWorkName,
          type: form.value.genderOrientation,
          description: form.value.workDescription,
          tag: form.value.workCategories.join('||'),
          cover: form.value.fileList[0],
        }).then(response => {
          ElMessage.success(response.data);
          emit('update:isDialogVisible', false);
        }).catch(error => {
          ElMessage.error('创建失败');
        });
    } else {
      ElMessage.error('请检查表单填写');
    }
  });
};

</script>

<style scoped>
.uploadworkbox span {
  font-size: 18px;
  display: flex;   
}
.uploadworkbox .el-form{
  width: 60%;
}
.tag-group{
  display: flex;
  flex-wrap: wrap;
  row-gap: 4px;
}
.tag-group .el-tag--plain {
    color: black;
    font-size: 12px;
    border-color: #efefef;
    margin-right: 10px;
    cursor: pointer;
}
.tag-group .active {
    color: #3e79ff;
    background-color: #ecf5ff;
    border: 1px solid #9eb5ed;
}
.image-preview {
  width: 100%;
  border-radius: 4px;
}
</style>